package com.xinQing.blogme.conf.mybatis;

import com.xinQing.blogme.util.ApplicationContextHolder;
import com.xinQing.blogme.util.Check;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.cache.Cache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisServerCommands;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * redis实现mybatis的二级缓存
 *
 * 为了防止程序出现未知风险，不采用mybatis二级缓存
 *
 * Created by null on 2017/8/3.
 */
@Slf4j
@Deprecated
public class RedisCache implements Cache {

    // redis过期时间
    private static final long EXPIRE_TIME_IN_MINUTES = 30;

    private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock(true);

    private final String id;

    private RedisTemplate redisTemplate;

    public RedisCache(String id) {
        if (id == null) {
            throw new IllegalArgumentException("Cache instances require an ID");
        }
        log.debug("MybatisRedisCache:id = {}", id);
        this.id = id;
    }

    @Override
    public String getId() {
        return id;
    }

    @Override
    public void putObject(Object key, Object value) {
        if (Check.isNull(value)) {
            return;
        }
        try {
            ValueOperations opsForValue = getRedisTemplate().opsForValue();
            opsForValue.set(key, value, EXPIRE_TIME_IN_MINUTES, TimeUnit.MINUTES);
            log.debug("Put query result to redis");
        } catch (Throwable t) {
            log.error("Redis put failed", t);
        }
    }

    @Override
    public Object getObject(Object key) {
        try {
            ValueOperations opsForValue = getRedisTemplate().opsForValue();
            log.debug("Get cached query result from redis");
            return opsForValue.get(key);
        } catch (Throwable t) {
            log.error("Redis get failed, fail over to db", t);
            return null;
        }
    }

    @Override
    public Object removeObject(Object key) {
        try {
            getRedisTemplate().delete(key);
            log.debug("Remove cached query result from redis");
        } catch (Throwable t) {
            log.error("Redis remove failed", t);
        }
        return null;
    }

    @Override
    public void clear() {
        getRedisTemplate().execute((RedisCallback) connection -> {
            connection.flushDb();
            return null;
        });
        log.debug("Clear all the cached query result from redis");
    }

    @Override
    public int getSize() {
        Object execute = getRedisTemplate().execute(RedisServerCommands::dbSize);
        return ((Long) execute).intValue();
    }

    @Override
    public ReadWriteLock getReadWriteLock() {
        return readWriteLock;
    }

    private RedisTemplate getRedisTemplate() {
        if (redisTemplate == null) {
            redisTemplate = ApplicationContextHolder.getBean("redisTemplate", RedisTemplate.class);
        }
        return redisTemplate;
    }
}